
const express = require('express');
const router = express.Router();
const pool = require('../config/bd');
const { validate: isValidUUID } = require('uuid');

//获取所有用户信息
router.get('/users', async (req, res) => {
  try {
    // 分页参数处理（默认第一页，每页20条）
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 20;
    const offset = (page - 1) * pageSize;

    // SQL查询（排除密码字段）[3,7](@ref)
    const [results] = await pool.query(
      `SELECT 
        id, username, nickname, 
        DATE_FORMAT(birthday, '%Y-%m-%d') AS birthday,
        gender, avatar, phone, family_id, family_name,
        created_at
       FROM user
       LIMIT ? OFFSET ?`,
      [pageSize, offset]
    );

    // 获取总数用于分页计算
    const [total] = await pool.query('SELECT COUNT(*) AS total FROM user');

    res.json({
      code: 200,
      success: true,
      data: {
        items: results,
        pagination: {
          total: total[0].total,
          currentPage: page,
          pageSize: pageSize,
          totalPages: Math.ceil(total[0].total / pageSize)
        }
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ code: 500, message: '服务器内部错误' });
  }
});

// 添加家庭成员信息（支持自动建立全家庭关系）
router.post('/family/members', async (req, res) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const { operatorId, targetUserId, familyId, relation } = req.body;

    // 强化参数校验
    if (!isValidUUID(operatorId) || !isValidUUID(targetUserId)) {
      return res.status(400).json({ code: 400, message: 'ID格式异常' });
    }

    // 验证操作者家庭权限
    const [operator] = await connection.query(
      `SELECT family_id, family_name FROM user WHERE id = ?`,
      [operatorId]
    );
    if (operator[0]?.family_id !== familyId) {
      return res.status(403).json({ code: 403, message: '无家庭操作权限' });
    }

    // 获取目标用户完整信息
    const [targetUser] = await connection.query(
      `SELECT id, family_id FROM user WHERE id = ?`,
      [targetUserId]
    );
    if (!targetUser.length) {
      return res.status(404).json({ code: 404, message: '目标用户不存在' });
    }

    // 家庭关系迁移（原家庭解除）
    if (targetUser[0].family_id) {
      await connection.query(
        `DELETE FROM family_member 
         WHERE family_id = ? AND member_id = ?`,
        [targetUser[0].family_id, targetUserId]
      );
    }

    // 更新用户家庭归属
    await connection.query(
      `UPDATE user SET 
        family_id = ?,
        updated_at = CURRENT_TIMESTAMP 
       WHERE id = ?`,
      [familyId, targetUserId]
    );

    // 获取家庭所有现有成员（排除新成员自己）
    const [familyMembers] = await connection.query(
      `SELECT id 
       FROM user 
       WHERE family_id = ? 
         AND id != ?`,
      [familyId, targetUserId]
    );

    // 构建关系插入数据
    const insertValues = [];

    // 添加操作者与新成员的双向关系[3](@ref)
    insertValues.push([operatorId, targetUserId, familyId, relation]);
    insertValues.push([targetUserId, operatorId, familyId, 'reverse']);

    // 添加新成员与所有家庭成员的关系
    familyMembers.forEach(member => {
      const existingId = member.id;
      // 现有成员→新成员关系（正向）
      insertValues.push([existingId, targetUserId, familyId, 'family']);
      // 新成员→现有成员关系（反向）
      insertValues.push([targetUserId, existingId, familyId, 'reverse']);
    });

    // 批量插入关系（忽略重复项）[1](@ref)
    if (insertValues.length > 0) {
      await connection.query(
        `INSERT IGNORE INTO family_member 
         (user_id, member_id, family_id, relation_type)
         VALUES ?`,
        [insertValues]
      );
    }

    await connection.commit();

    res.status(201).json({
      code: 201,
      data: {
        newMemberId: targetUserId,
        familyName: operator[0].family_name,
        establishedRelations: insertValues.length / 2 // 双向关系计数
      }
    });

  } catch (error) {
    await connection.rollback();
    console.error('添加失败:', error);
    res.status(500).json({
      code: 500,
      message: error.code === 'ER_DUP_ENTRY'
        ? '部分关系已存在'
        : '事务处理异常'
    });
  } finally {
    connection.release();
  }
});

//获取家庭成员信息
router.get('/family/members', async (req, res) => {
  const connection = await pool.getConnection();
  try {
    // 分页参数处理
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 20;
    const offset = (page - 1) * pageSize;

    // 通过token获取当前用户信息（示例使用参数传递，实际应通过中间件获取）
    const { userId } = req.query;
    if (!isValidUUID(userId)) {
      return res.status(400).json({ code: 400, message: '用户ID格式异常' });
    }

    // 获取用户家庭信息[7](@ref)
    const [userInfo] = await connection.query(
      `SELECT family_id, family_name 
       FROM user 
       WHERE id = ?`,
      [userId]
    );

    if (!userInfo.length || !userInfo[0].family_id) {
      return res.status(404).json({ code: 404, message: '用户未加入家庭' });
    }

    const familyId = userInfo[0].family_id;

    // 获取家庭成员详细信息[1,7](@ref)
    const [members] = await connection.query(
      `SELECT 
        DISTINCT u.id,  -- 关键去重
        u.username,
        u.nickname,
        DATE_FORMAT(u.birthday, '%Y-%m-%d') AS birthday,
        u.gender,
        u.avatar,
        u.phone,
        MAX(fm.relation_type) AS relation_type,  -- 取最新或任意关系
        MAX(fm.create_time) AS join_time
       FROM user u
       JOIN family_member fm ON u.id = fm.member_id
       WHERE fm.family_id = ?
       GROUP BY u.id  -- 按成员分组
       ORDER BY join_time DESC
       LIMIT ? OFFSET ?`,
      [familyId, pageSize, offset]
    );

    // 获取总数[3](@ref)
    const [total] = await connection.query(
      `SELECT COUNT(DISTINCT u.id) AS total
       FROM user u
       JOIN family_member fm ON u.id = fm.member_id
       WHERE fm.family_id = ?`,
      [familyId]
    );

    res.json({
      code: 200,
      success: true,
      data: {
        familyName: userInfo[0].family_name,
        items: members.map(member => ({
          ...member,
          // 转换关系类型为中文
          relation_type: relationTypeMapping(member.relation_type)
        })),
        pagination: {
          total: total[0].total,
          currentPage: page,
          pageSize: pageSize,
          totalPages: Math.ceil(total[0].total / pageSize)
        }
      }
    });

  } catch (error) {
    console.error('获取家庭成员失败:', error);
    res.status(500).json({ code: 500, message: '数据库查询异常' });
  } finally {
    connection.release();
  }
});

// 关系类型映射（根据业务需求扩展）
function relationTypeMapping(type) {
  const mappings = {
    'parent': '家长',
    'child': '子女',
    'spouse': '配偶',
    'sibling': '兄弟姐妹',
    'other': '其他亲属'
  };
  return mappings[type] || '家庭成员';
}


module.exports = router;